import {
  sysUserLogin,
  teacherLogin,
  getInfo,
  logout
} from '@/api/login'

const user = {
  state: {
    token: window.localStorage.getItem("token"),
    name: window.localStorage.getItem("name"),
    role: window.localStorage.getItem("role"),
    permission: window.localStorage.getItem("permission"),
    subjects: window.localStorage.getItem("subjects")
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
      window.localStorage.setItem("token", token);
    },
    SET_NAME: (state, name) => {
      state.name = name;
      window.localStorage.setItem("name", name);
    },
    SET_ROLE: (state, roles) => {
      state.role = roles;
      window.localStorage.setItem("role", roles);
    },
    SET_PERMISSION: (state, permission) => {
      state.permission = permission;
      window.localStorage.setItem("permission", permission);
    },
    SET_SUBJECTS: (state, subjects) => {
      state.subjects = subjects;
      window.localStorage.setItem("subjects", subjects);
    }
  },

  actions: {
    Token({ commit }, token) {
      commit("SET_TOKEN", token);
      getInfo().then(res => {
        commit("SET_ROLE", res.data.role);
        commit("SET_NAME", res.data.name);
        commit("SET_PERMISSION", res.data.permission);
        commit("SET_SUBJECTS", res.data.subjects);
      });
    },
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      return new Promise((resolve, reject) => {
        commit("SET_TOKEN", null);
          sysUserLogin(username, userInfo.password)
            .then(response => {
              const data = response.data;
              commit("SET_TOKEN", data.token);
              commit("SET_ROLE", data.role);
              commit("SET_NAME", data.name);
              commit("SET_PERMISSION", data.permission);
              commit("SET_SUBJECTS", data.subjects);
              resolve();
            })
            .catch(error => {
              reject(error);
            });
      });
    },
    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        logout()
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_ROLE", "");
            commit("SET_NAME", "");
            commit("SET_PERMISSION", "");
            commit("SET_SUBJECTS", "");
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit("SET_TOKEN", "");
        commit("SET_TOKEN", "");
        commit("SET_ROLE", "");
        commit("SET_NAME", "");
        commit("SET_PERMISSION", "");
        commit("SET_SUBJECTS", "");
        resolve();
      });
    }
  }
};

export default user
